<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item><i
          class="iconfont icon-r-user1"
          style="margin: 5px; font-size: 22px"
      >
        用户信息管理</i></el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input
              placeholder="请输入用户名"
              v-model="queryInfo.username"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-input
              placeholder="请输入姓名"
              v-model="queryInfo.nike"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-input
              placeholder="请输入车牌号"
              v-model="queryInfo.card"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-button
              type="primary"
              style="font-size: 18px"
              @click="search()"
          ><i class="iconfont icon-r-find" style="font-size: 22px;"></i>
            搜索
          </el-button
          >
        </el-col>
        <el-col :span="4">
          <el-button
              type="success"
              style="font-size: 18px"
              @click="addUser"
          ><i class="iconfont icon-r-add" style="font-size: 22px;"></i>
            新增
          </el-button
          >
        </el-col>
        <el-col :span="4">
          <el-button
              type="warning"
              style="font-size: 18px"
              @click="feeUserShow = true"
          ><i class="iconfont icon-r-shield" style="font-size: 22px;"></i>
            充值
          </el-button
          >
        </el-col>
      </el-row>

      <!-- 车位信息区域 -->
      <el-table v-loading="loading" :data="users" border stripe>
        <el-table-column
            width="50"
            label="序号"
            align="center"
            type="index"
        ></el-table-column>
        <el-table-column label="用户名" prop="username" align="center">
        </el-table-column>
        <el-table-column label="姓名" prop="nike" align="center">
        </el-table-column>
        <el-table-column label="性别" prop="sex" align="center">
        </el-table-column>
        <el-table-column label="联系电话" prop="phone" align="center">
        </el-table-column>
        <el-table-column label="车牌号" prop="card" align="center">
        </el-table-column>
        <el-table-column label="账户余额" prop="money" align="center">
          <template slot-scope="scope">
                        <span v-if="scope.row.money"
                        >{{ scope.row.money }}元</span
                        >
            <span v-else>0元</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template slot-scope="scope">
            <el-button
                v-if="scope.row.username !== 'admin'"
                @click="toEdit(scope.row)"
                type="primary"
                circle
            ><i class="iconfont icon-r-edit" style="font-size: 24px"></i></el-button>
            <el-button
                v-if="scope.row.username !== 'admin'"
                @click="rePassword(scope.row.uid)"
                type="warning"
                circle
            ><i class="iconfont icon-r-lock" style="font-size: 24px"></i></el-button>
            <el-button
                v-if="scope.row.username !== 'admin'"
                @click="userDelete(scope.row.uid)"
                type="danger"
                circle
            ><i class="iconfont icon-r-delete" style="font-size: 24px"></i></el-button>
            <el-button
                v-if="scope.row.username === 'admin'"
                @click="toEdit(scope.row)"
                type="primary"
                circle
                disabled
            ><i class="iconfont icon-r-edit" style="font-size: 24px"></i></el-button>
            <el-button
                disabled
                v-if="scope.row.username === 'admin'"
                @click="userDelete(scope.row.uid)"
                type="danger"
                circle
            ><i class="iconfont icon-r-delete" style="font-size: 24px"></i></el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog
        title="修改用户"
        :visible.sync="editShow"
        width="450px"
        center
        @close="editClose"
    >
      <!-- 内容主题区域 -->
      <el-form
          :model="editUser"
          :rules="editRules"
          ref="editRules"
          label-width="80px"
      >
        <el-form-item label="姓名" prop="nike" class="is-required">
          <el-input
              v-model="editUser.nike"
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" class="is-required">
          <el-input
              v-model="editUser.password"
              show-password
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="余额" prop="money" class="is-required">
          <el-input
              v-model.number="editUser.money"
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" class="is-required">
          <el-input
              v-model="editUser.phone"
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="车牌号" prop="card" class="is-required">
          <el-input
              v-model="editUser.card"
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" class="is-required">
          <template>
            <el-radio v-model="editUser.sex" label="男"
            >男
            </el-radio
            >
            <el-radio v-model="editUser.sex" label="女"
            >女
            </el-radio
            >
          </template>
        </el-form-item>
        <el-form-item label="年龄" prop="age" class="is-required">
          <el-input
              v-model.number="editUser.age"
              style="width: 300px"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
                <el-button @click="editClose()" style="font-size: 18px;"><i class="iconfont icon-r-left"
                                                                            style="font-size: 22px;"></i> 取消</el-button>
                <el-button type="primary" @click="editCommit('editRules')"
                           style="font-size: 18px;"><i class="iconfont icon-r-yes" style="font-size: 22px;"></i> 确认修改</el-button
                >
            </span>
    </el-dialog>
    <el-dialog
        title="新增用户"
        :visible.sync="addShow"
        width="500px"
        style="margin-top: -10vh;"
        center
        @close="addClose"
    >
      <!-- 内容主题区域 -->
      <el-form
          :model="registerUser"
          status-icon
          :rules="registerRules"
          ref="registerRules"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item
            label="用户名"
            prop="username"
            class="is-required"
        >
          <el-input
              v-model="registerUser.username"
              placeholder="请输入用户名"
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" class="is-required">
          <el-input
              v-model="registerUser.password"
              placeholder="请输入密码"
              show-password
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="nike" class="is-required">
          <el-input
              v-model="registerUser.nike"
              placeholder="请输入姓名"
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex" class="is-required">
          <el-radio v-model="registerUser.sex" label="男"
          >男
          </el-radio
          >
          <el-radio v-model="registerUser.sex" label="女"
          >女
          </el-radio
          >
        </el-form-item>
        <el-form-item label="年龄" prop="age" class="is-required">
          <el-input
              v-model.number="registerUser.age"
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="车牌号" prop="card" class="is-required">
          <el-input
              v-model="registerUser.card"
              placeholder="请输入车牌号"
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" class="is-required">
          <el-input
              v-model="registerUser.phone"
              placeholder="请输入联系电话"
              style="width: 300px"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
                <el-button
                    @click="addClose()"
                    style="font-size: 18px;">
                  <i class="iconfont icon-r-left" style="font-size: 22px;"></i>
                  取消
                </el-button>
                <el-button
                    type="primary"
                    @click="submitForm('registerRules')"
                    style="font-size: 18px;">
                  <i class="iconfont icon-r-yes" style="font-size: 22px;"></i>
                  确认添加
                </el-button>
      </span>
    </el-dialog>

    <el-dialog
        title="用户充值"
        :visible.sync="feeUserShow"
        width="50%"
        center
        @close="feeUserShow = false"
    >
      <el-form
          :model="feeUser"
          :rules="feeUserRules"
          ref="feeUserRules"
          label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="feeUser.username"></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input v-model="feeUser.money"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
          <el-button @click="feeUserShow = false" style="font-size: 18px;">
            <i class="iconfont icon-r-left" style="font-size: 22px;"></i> 取消
          </el-button>
          <el-button type="primary" @click="feeUserCon('feeUserRules')">
            确认充值
          </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "UserMane",
  data() {

    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      }
      setTimeout(() => {
        axios.post("/api/user/checkUsername/" + value).then((res) => {
          if (res.data.data) {
            callback(new Error("用户名已存在"));
          } else {
            callback();
          }
        });
      }, 10);
    };
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("年龄不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (value < 18) {
            callback(new Error("必须年满18岁"));
          } else {
            callback();
          }
        }
      }, 1000);
    };


    return {
      total: 0,
      loading: true,
      queryInfo: {
        username: "",
        nike: "",
        card: "",
        pagenum: 1,
        pageSize: 5,
      },
      users: [],
      editUser: {
        password: "",
        nike: "",
        sex: "",
        age: "",
        phone: "",
        money: "",
        card: "",
      },
      registerUser: {
        sex: "男",
      },
      addShow: false,
      editShow: false,
      editRules: {
        niek: [
          {required: true, message: "请输入姓名", trigger: "blur"},
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        age: [{validator: checkAge, trigger: "blur"}],
        phone: [
          {
            required: true,
            message: "请输入联系电话",
            trigger: "blur",
          },
        ],
        card: [
          {
            required: true,
            message: "请输入车牌号",
            trigger: "blur",
          },
        ],
      },
      registerRules: {
        username: [{validator: checkUsername, trigger: "blur"}],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        niek: [
          {required: true, message: "请输入姓名", trigger: "blur"},
        ],
        age: [{validator: checkAge, trigger: "blur"}],
        phone: [
          {
            required: true,
            message: "请输入联系电话",
            trigger: "blur",
          },
        ],
        card: [
          {
            required: true,
            message: "请输入车牌号",
            trigger: "blur",
          },
        ],
      },
      feeUserShow: false,
      feeUserRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        money: [
          {
            required: true,
            message: "请输入充值金额",
            trigger: "blur",
          },
        ],
      },
      feeUser: {
        username: "",
        money: "",
      },
    }
  },
  mounted() { // 等待页面挂载完，初始化数据
    this.getList();
  },
  methods: {
    feeUserCon(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('提交成功');
          console.log(this.feeUser);
          axios.put('/api/fee/userFee', this.feeUser).then(response => {
            if (response.data.flag) {
              this.$message({
                message: response.data.message,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.feeUserShow = false;
                }
              })
              this.getList()
            } else {
              this.$message({
                message: response.data.message,
                type: "error",
                duration: 1000,
                onClose: () => {
                  this.feeUserShow = false;
                }
              });
            }
          })
        } else {
          this.$message({
            message: "请输入正确的信息",
            type: "error",
            duration: 1000,
          });
        }

      });
    },
    getList() {
      axios.get('/api/user/getUsers', {
        params: this.queryInfo
      }).then(response => {
        this.loading = false;
        this.total = response.data.data.total;
        this.users = response.data.data.records;
      })
    },
    search() {
      axios.post('/api/user/search', this.queryInfo).then(response => {
        this.total = response.data.data.total;
        this.users = response.data.data.records;
      })
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getList()
    },
    addUser() {
      for (let item in this.registerUser) {
        this.registerUser[item] = "";
      }
      this.registerUser.sex = "男";
      this.addShow = true;
    },
    editClose() {
      this.editShow = false;
      this.$nextTick(() => {
        this.$refs.registerRules.resetFields();
      });
    },
    toEdit(row) {
      this.editShow = true
      for (let item in row) {
        this.editUser[item] = row[item];
      }
    },
    editCommit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.put('/api/user/editUser', this.editUser).then(response => {
            if (response.data.flag) {
              this.$message({
                message: response.data.message,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.editClose()
                }
              });
            } else {
              this.$message({
                message: response.data.message,
                type: "error",
                duration: 1000,
                onClose: () => {
                  this.editShow = false;
                }
              });
            }
          })
        } else {
          return false;
        }
      })
    },
    userDelete(uid) {
      console.log(uid)
      this.$confirm(`此操作将永久删除【${uid}号车主】, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/api/user/deleteUser/' + uid).then(response => {
          if (response.data.flag) {
            this.$message({
              type: 'success',
              message: response.data.message,
              duration: 1000,
              onClose: () => {
                this.getList()
              }
            });
          } else {
            this.$message({
              type: 'error',
              message: response.data.message,
              duration: 1000,
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
          duration: 1000,
        });
      });
    },
    rePassword(uid) {
      this.$prompt('请输入密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d{1,20}$/,  // 匹配1到20位的数字
        inputErrorMessage: '密码应为1到20位的数字'
      }).then(({ value }) => {
        axios.put(`/api/user/rePassword/${uid}/${value}`).then(response => {
          if (response.data.flag) {
            this.$message({
              type: 'success',
              message: response.data.message,
              duration: 1000
            });
          } else {
            this.$message({
              type: 'error',
              message: response.data.message,
              duration: 1000
            });
          }
        })
        // 你可以在这里添加提交密码的逻辑，比如调用API
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    addClose() {
      this.addShow = false;
      this.$nextTick(() => {
        this.$refs.registerRules.resetFields();
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.post('/api/user/register', this.registerUser).then(response => {
            console.log(response.data)
            if (response.data.flag) {
              this.$message.success({
                message: response.data.message,
                type: "success",
                duration: 1000,
              });
            } else {
              this.$message.error({
                message: response.data.message,
                type: "warning",
                duration: 1000,
              });
            }
            this.addClose()
          })
        } else {
          return false;
        }
      })
    },
  }
}
</script>

<style scoped>

</style>
